﻿using System;
using System.Linq;
using Csla;
using Csla.Data;
using Csla.Serialization;
using BizControl.DalLinq;
using BizControl.Library.BusinessObjects.People;
using BizControl.Library.Security;
using System.Security;
using BizControl.Resources;

namespace BizControl.Library.BusinessObjects.Models
{
  [Serializable()]
  public class ModelList : ReadOnlyListBase<ModelList, ModelInfo>
  {
    #region  Factory Methods

    public static ModelList GetModelList()
    {
      return DataPortal.Fetch<ModelList>();
    }

    public static ModelList GetModelList(string name)
    {
      return DataPortal.Fetch<ModelList>(new SingleCriteria<ModelList, string>(name));
    }

    private ModelList()
    { /* require use of factory methods */ }

    #endregion

    #region  Data Access

    private void DataPortal_Fetch()
    {
      // fetch with no filter
      Fetch("");
    }

    private void DataPortal_Fetch(SingleCriteria<ModelList, string> criteria)
    {
      Fetch(criteria.Value);
    }

    private void Fetch(string nameFilter)
    {
      var currentUser = SecurityChecks.GetCurrentUser();
      RaiseListChangedEvents = false;
      using (var ctx = ContextManager<BusinessControl2DataContext>.GetManager(Database.BizControlDB))
      {
        var data = from p in ctx.DataContext.Models
                   from pm in ctx.DataContext.PersonModels
                   where !p.IsDeleted && pm.ModelId == p.ModelId && pm.PersonId == currentUser.PersonId
                   select new ModelInfo(p.ModelId, p.Name);
        if (!(string.IsNullOrEmpty(nameFilter)))
        {
          data = from p in ctx.DataContext.Models
                 from pm in ctx.DataContext.PersonModels
                 where p.Name.Contains(nameFilter) && !p.IsDeleted && pm.ModelId == p.ModelId && pm.PersonId == currentUser.PersonId
                 select new ModelInfo(p.ModelId, p.Name);
        }
        IsReadOnly = false;
        this.AddRange(data);
        IsReadOnly = true;
      }
      RaiseListChangedEvents = true;
    }

    #endregion

  }
}
